/**
 * @file 地图与位置状态管理模块
 * @description 统一管理地图与位置状态，整合mapService到Pinia store
 * @date 2024-08-14
 */

import { defineStore } from 'pinia';
// 使用正确的导入语法，添加@ts-ignore注释避免uni-app环境下的TS错误
// @ts-ignore
import { ref, computed } from 'vue';
import { mapService, MapEventType, MapLoadOptions } from '@/services/mapService';
import { BAIDU_MAP_CONFIG } from '@/config/map.config';
import { logger } from '@/utils/system/logger';
import type { MapState } from '@/types/state';

/**
 * 地图与位置状态管理模块
 */
export const useMapStore = defineStore('map', () => {
  // ========== 地图状态 ==========
  const status = ref(mapService.state.status.value);
  const error = ref(mapService.state.error.value);
  const capabilities = ref(mapService.state.capabilities.value);
  const loading = ref(mapService.state.loading.value);
  const loadingTrack = ref(mapService.state.loadingTrack.value);
  const lastLoadTime = ref(mapService.state.lastLoadTime.value);
  
  // 地图配置状态
  const mapType = ref<'normal' | 'satellite' | 'hybrid'>(
    BAIDU_MAP_CONFIG.defaultOptions.defaultType as 'normal'
  );
  const zoom = ref(BAIDU_MAP_CONFIG.defaultOptions.zoom);
  const center = ref(BAIDU_MAP_CONFIG.defaultCenter);
  const showTraffic = ref(false);
  const showBuildings = ref(true);
  const enable3D = ref(true);

  // ========== 位置状态 ==========
  const isWatching = ref(false);
  const currentLocation = ref<UniApp.OnLocationChangeCallbackResult | null>(null);
  const watchId = ref<number | null>(null);
  const locationError = ref<string | null>(null);
  const locationPermissionGranted = ref(false);

  // 计算属性
  const isMapReady = computed(() => 
    capabilities.value.mapLoaded && 
    status.value === 'loaded'
  );

  const isTrackReady = computed(() => 
    isMapReady.value && 
    capabilities.value.trackPluginLoaded
  );

  const hasLocation = computed(() => currentLocation.value !== null);

  const shouldCenterOnLocation = computed(() => 
    isMapReady.value && 
    hasLocation.value && 
    isWatching.value
  );
  
  /**
   * 初始化store，连接mapService事件
   */
  function init() {
    // 同步初始状态
    syncStateFromService();
    
    // 订阅mapService事件
    const unsubscribers = [
      mapService.on('map:loading', () => {
        loading.value = true;
      }),
      
      mapService.on('map:loaded', () => {
        status.value = 'loaded';
        loading.value = false;
        capabilities.value.mapLoaded = true;
        lastLoadTime.value = Date.now();
      }),
      
      mapService.on('map:error', (data) => {
        status.value = 'error';
        loading.value = false;
        error.value = data?.error || '地图加载失败';
      }),
      
      mapService.on('track:loading', () => {
        loadingTrack.value = true;
      }),
      
      mapService.on('track:loaded', () => {
        capabilities.value.trackPluginLoaded = true;
        loadingTrack.value = false;
      }),
      
      mapService.on('track:error', (data) => {
        loadingTrack.value = false;
        error.value = data?.error || '轨迹插件加载失败';
      }),
      
      mapService.on('status-change', (data) => {
        status.value = data.status;
        error.value = data.error;
      })
    ];
    
    // 返回清理函数
    return () => {
      unsubscribers.forEach(unsub => unsub());
      stopLocationUpdate(); // 确保位置监听被停止
    };
  }

  /**
   * 同步服务状态到store
   */
  function syncStateFromService() {
    status.value = mapService.state.status.value;
    error.value = mapService.state.error.value;
    capabilities.value = mapService.state.capabilities.value;
    loading.value = mapService.state.loading.value;
    loadingTrack.value = mapService.state.loadingTrack.value;
    lastLoadTime.value = mapService.state.lastLoadTime.value;
  }

  /**
   * 按需加载地图
   */
  async function loadMapOnDemand(options?: MapLoadOptions): Promise<boolean> {
    try {
      // 同步状态，确保store状态与服务一致
      loading.value = true;
      
      // 调用服务方法加载地图
      const result = await mapService.loadMapOnDemand(options);
      
      // 加载后再次同步状态
      syncStateFromService();
      
      return result;
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载地图失败';
      status.value = 'error';
      loading.value = false;
      return false;
    }
  }

  /**
   * 加载轨迹插件
   */
  async function loadTrackPlugin(): Promise<boolean> {
    try {
      loadingTrack.value = true;
      const result = await mapService.loadTrackPlugin();
      syncStateFromService();
      return result;
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载轨迹插件失败';
      loadingTrack.value = false;
      return false;
    }
  }

  /**
   * 检查当前路由是否需要地图
   */
  function isMapRouteActive(): boolean {
    return mapService.isMapRouteActive();
  }

  /**
   * 检查地图资源状态
   */
  function checkMapResources(forceUpdate = false): boolean {
    const result = mapService.checkMapResources(forceUpdate);
    syncStateFromService();
    return result.mapLoaded && result.trackPluginLoaded;
  }

  /**
   * 更新地图类型
   */
  function setMapType(type: 'normal' | 'satellite' | 'hybrid'): void {
    mapType.value = type;
  }

  /**
   * 更新地图缩放级别
   */
  function setZoom(level: number): void {
    if (level >= BAIDU_MAP_CONFIG.defaultOptions.minZoom && 
        level <= BAIDU_MAP_CONFIG.defaultOptions.maxZoom) {
      zoom.value = level;
    }
  }

  /**
   * 更新地图中心点
   */
  function setCenter(lng: number, lat: number): void {
    center.value = { lng, lat };
  }

  /**
   * 切换交通图层
   */
  function toggleTraffic(): void {
    showTraffic.value = !showTraffic.value;
  }

  /**
   * 切换建筑物显示
   */
  function toggleBuildings(): void {
    showBuildings.value = !showBuildings.value;
  }

  /**
   * 切换3D视图
   */
  function toggle3DView(): void {
    enable3D.value = !enable3D.value;
  }

  // ========== 位置相关方法 ==========

  /**
   * 请求位置权限
   */
  const requestLocationPermission = async (): Promise<boolean> => {
    try {
      await new Promise<void>((resolve, reject) => {
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => resolve(),
          fail: (error) => reject(error)
        });
      });
      locationPermissionGranted.value = true;
      locationError.value = null;
      return true;
    } catch (error) {
      locationError.value = '获取位置权限失败';
      locationPermissionGranted.value = false;
      return false;
    }
  }

  /**
   * 获取当前位置
   */
  const getCurrentLocation = async (): Promise<UniApp.GetLocationSuccess | null> => {
    try {
      const res = await new Promise<UniApp.GetLocationSuccess>((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          highAccuracyExpireTime: 3000,
          success: (res) => resolve(res),
          fail: (error) => reject(error)
        });
      });
      
      currentLocation.value = res;
      locationError.value = null;
      
      // 如果地图已加载且配置为自动居中，则更新地图中心点
      if (isMapReady.value) {
        setCenter(res.longitude, res.latitude);
      }
      
      return res;
    } catch (error) {
      locationError.value = '获取位置信息失败';
      return null;
    }
  }

  /**
   * 开始位置监听
   * @param updateMap 是否自动更新地图中心点
   */
  const startLocationUpdate = (updateMap = false) => {
    if (isWatching.value) return;

    try {
      const watch = uni.onLocationChange((res) => {
        currentLocation.value = res;
        
        // 如果配置为自动更新地图中心点且地图已加载
        if (updateMap && isMapReady.value) {
          setCenter(res.longitude, res.latitude);
        }
      });

      watchId.value = watch as unknown as number;
      isWatching.value = true;

      // 开启持续定位
      uni.startLocationUpdate({
        success: () => {
          logger.info('开启持续定位成功');
          locationError.value = null;
        },
        fail: (error) => {
          logger.error('开启持续定位失败:', error);
          locationError.value = '开启持续定位失败';
          stopLocationUpdate();
        }
      });
    } catch (error) {
      locationError.value = '位置监听设置失败';
      logger.error('设置位置监听失败:', error);
    }
  }

  /**
   * 停止位置监听
   */
  const stopLocationUpdate = () => {
    if (!isWatching.value) return;

    if (watchId.value) {
      uni.offLocationChange(function() {
        logger.info('停止位置监听');
      });
      watchId.value = null;
    }

    uni.stopLocationUpdate({
      success: () => {
        logger.info('停止持续定位成功');
      },
      fail: (error: any) => {
        logger.error('停止持续定位失败:', error);
      },
      complete: () => {
        isWatching.value = false;
      }
    });
  }

  /**
   * 定位并居中地图
   * 获取当前位置并将地图中心设置到该位置
   */
  const locateAndCenterMap = async (): Promise<boolean> => {
    try {
      if (!isMapReady.value) {
        await loadMapOnDemand();
      }
      
      const location = await getCurrentLocation();
      if (location) {
        setCenter(location.longitude, location.latitude);
        return true;
      }
      return false;
    } catch (error) {
      locationError.value = '定位并居中地图失败';
      logger.error('定位并居中地图失败:', error);
      return false;
    }
  }

  // 初始化
  const cleanup = init();
  
  // 返回store状态和方法
  return {
    // 地图状态
    status,
    error,
    capabilities,
    loading,
    loadingTrack,
    lastLoadTime,
    mapType,
    zoom,
    center,
    showTraffic,
    showBuildings,
    enable3D,
    
    // 位置状态
    isWatching,
    currentLocation,
    locationError,
    locationPermissionGranted,
    
    // 计算属性
    isMapReady,
    isTrackReady,
    hasLocation,
    shouldCenterOnLocation,
    
    // 地图方法
    loadMapOnDemand,
    loadTrackPlugin,
    isMapRouteActive,
    checkMapResources,
    setMapType,
    setZoom,
    setCenter,
    toggleTraffic,
    toggleBuildings,
    toggle3DView,
    
    // 位置方法
    requestLocationPermission,
    getCurrentLocation,
    startLocationUpdate,
    stopLocationUpdate,
    locateAndCenterMap,
    
    // 原始mapService，用于兼容现有逻辑
    mapService,
    
    // 生命周期清理
    cleanup
  };
}); 